package com.weaver.qfengx;

import com.alibaba.fastjson.JSON;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;

import java.util.HashMap;
import java.util.Map;

/**
 * 基于HttpClient的封装
 */
public class HttpClientUtils {

    // doGet请求
    public static CloseableHttpResponse doGet(CloseableHttpClient httpClient, String url, Map<String, String> headers, Map<String, String> params) throws Exception {
        // 添加参数
        URIBuilder uriBuilder = new URIBuilder(url);
        for (Map.Entry<String, String> entry : params.entrySet()) {
            uriBuilder.setParameter(entry.getKey(), entry.getValue());
        }
        HttpGet httpGet = new HttpGet(uriBuilder.build());
        // 添加请求头
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpGet.setHeader(entry.getKey(), entry.getValue());
        }
        return httpClient.execute(httpGet);
    }

    public static CloseableHttpResponse doGet(CloseableHttpClient httpClient, String url, Map<String, String> params) throws Exception {
        return doGet(httpClient, url, new HashMap<>(), params);
    }

    public static CloseableHttpResponse doGet(String url, Map<String, String> params) throws Exception {
        return doGet(HttpClients.createDefault(), url, new HashMap<>(), params);
    }

    // doPostByJson请求
    public static CloseableHttpResponse doPostByJson(CloseableHttpClient httpClient, String url, Map<String, String> headers, Map<String, Object> params) throws Exception {
        HttpPost httpPost = new HttpPost(url);
        StringEntity httpEntity = new StringEntity(JSON.toJSONString(params),"utf-8");
        httpPost.setHeader("Content-type","application/json");
        // 添加请求头
        for (Map.Entry<String, String> entry : headers.entrySet()) {
            httpPost.setHeader(entry.getKey(), entry.getValue());
        }
        httpPost.setEntity(httpEntity);
        return httpClient.execute(httpPost);
    }

    public static CloseableHttpResponse doPostByJson(CloseableHttpClient httpClient, String url, Map<String, Object> params) throws Exception {
        return doPostByJson(httpClient, url, new HashMap<>(), params);
    }

    public static CloseableHttpResponse doPostByJson(String url, Map<String, Object> params) throws Exception {
        return doPostByJson(HttpClients.createDefault(), url, new HashMap<>(), params);
    }
}
